const app = getApp()
let axios = require('../../utils/httpUtil.js');
let utils = require('../../utils/dateUtils.js')
let _map = require('../../utils/map.js')
// 合并不了
Page({
  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    shadowFlag: false,
    showFlag: true,
    shopList: [],
    queryType: 1,
    pageNum: 1,
    pageSize: 50,
    count: 5,
    hasMoreData: false,
    color3: 0,
    ispai: false,
    isSaix: false,
    shaixuan:0,
	address:"",
	optionsAdd:'',
    paiArr: [{
        name: '综合排序',
        type: 1
      },
      {
        name: '销量最高',
        type: 11
      },
      {
        name: '起送价最低',
        type: 12
      },
      {
        name: '配送费最低',
        type: 13
      }
    ],
    saiArr: [{
        name: '满减优惠',
        type: 4,
        state: false
      },
      {
        name: '新客立减',
        type: 5,
        state: false
      },
      {
        name: '单品折扣',
        type: 6,
        state: false
      }
    ],
    paiText: '综合排序',
    pIndex: 0,
  },
  openSetting: function(e) {
    console.log(e);
  },
  colse() {
    this.setData({
      ispai: false,
      isSaix: false,
      shaixuan:0
    })
  },
  getSysPhone(){
	  axios.reqPost('xshop/getTimePSet', {type:0},function(res){
		  wx.setStorageSync("platPhone",res.returnObject.phone);
	  })
  },
  dumpShopDetail(e){
    console.log(e.currentTarget.dataset.shopid);
    wx.navigateTo({
        url: '../shopInfo/shopInfo?shopId=' + e.currentTarget.dataset.shopid,
    })
  },
  getShopLists(message) {
    let self = this;
    wx.showLoading({
      title: message,
    })
    axios.reqPost('xshop/getShopsList', {
	  latitude: wx.getStorageSync('location').lat,
	  longitude: wx.getStorageSync('location').lng,
      queryType: this.data.queryType,
	  isRecommend: 1,
      pageNum: self.data.pageNum,
      pageSize: self.data.pageSize
    }, res => {
		console.log(res);
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      if (res.resultCode == 1000 && res.returnObject) {
        let contentlistTem = self.data.shopList
        if (self.data.pageNum == 1) {
          contentlistTem = []
        }
        let a = res.returnObject.list;
        a.map(p => {
			console.log(p);
          if (p.distance > 1000) {
            p.distance = (p.distance / 1000).toFixed(1) + 'km'
          } else {
            p.distance = p.distance + 'm'
          }
		  //计算起送价
			if (p.shopSendMinprice>0){
				p.shopSendMinprice = (p.shopSendMinprice/100).toFixed(2);
		  }else{
				p.shopSendMinprice = 0 ;
		  }
		  //计算配送费
			if (p.shopSendPrice > 0) {
				p.shopSendPrice = (p.shopSendPrice / 100).toFixed(2);
			}else{
				p.shopSendPrice = 0 ;
			}
          let tiflag;
          var tims = p.openHours.split(",");
          console.log(tims);
          for (var i = 0; i < tims.length; i++) {
            tiflag = utils.timeRange(tims[i].split("-")[0], tims[i].split("-")[1]);
            if (tiflag) {
              break;
            }
          }
          p.tiflag = tiflag;
          // console.log(p.tiflag)
          p.avgStar = (p.avgStar - 0).toFixed(1);
        });
        // for (var i = 0; i < 10; i++) {
        //   a.push(a[0])
        // }
        if (a.length < self.data.pageSize) {

          self.setData({
            shopList: contentlistTem.concat(a),
            hasMoreData: false
          })
        } else {
          self.setData({
            shopList: contentlistTem.concat(a),
            hasMoreData: true,
            pageNum: self.data.pageNum + 1
          })
        }
      } else {
        wx.showToast({
          title: '附近没有店铺',
          icon: 'none',
          duration: 2000
        })
		  self.setData({
			  shopList:'',
			  hasMoreData: false,
			  pageNum:  1
		  })
      }

    })
  },

  handleClickXun(e) {
    console.log(e)
    let color = e.currentTarget.dataset.color;
    if (color == 0) {
      this.setData({
        color3: color,
        ispai: true,
        isSaix: false,
        queryType: 1,
        pageNum: 1,
        shaixuan: 3
      })
      wx.createSelectorQuery().select('.tiaojian').boundingClientRect(function (rect) {
        console.log(rect);
        wx.pageScrollTo({
          scrollTop: rect.top
        })
      }).exec()

    } else if (color == 1) {
      this.setData({
        color3: color,
        ispai: false,
        queryType: 2,
        isSaix: false,
        pageNum: 1,
        shaixuan: 0
      })
      this.getShopLists('正在加载数据');
    } else if (color == 2) {
      this.setData({
        color3: color,
        ispai: false,
        queryType: 3,
        isSaix: false,
        pageNum: 1,
        shaixuan: 0
      })
      this.getShopLists('正在加载数据');
    } else if (color == 3) {
      this.setData({
        color3: color,
        ispai: false,
        isSaix: true,
        pageNum: 1,
        shaixuan:3
      })
      wx.createSelectorQuery().select('.tiaojian').boundingClientRect(function (rect) {
        console.log(rect);
        wx.pageScrollTo({
          scrollTop: rect.top
        })
      }).exec()
    }
  },
  choosePai(e) {
    let pIndex = e.currentTarget.dataset.index;
    let paiText = e.currentTarget.dataset.paitext;
    let queryType = e.currentTarget.dataset.type;
    this.setData({
      pIndex: pIndex,
      paiText: paiText
    })
    this.setData({
      ispai: false,
      isSaix: false,
      pageNum: 1,
      queryType: queryType,
      shaixuan:0
    })
    this.getShopLists('加载中...');
  },
  checkboxS(e) {
    let Index = e.currentTarget.dataset.index;
    this.data.saiArr[Index].state = true;
    this.setData({
      saiArr: this.data.saiArr
    });
  },
  clearArr() {
    this.data.saiArr.map(p => {
      p.state = false;
    })
    this.setData({
      saiArr: this.data.saiArr
    })
  },
  saveArr() {
    let str = [];
    this.data.saiArr.map(p => {
      p.state ? str.push(p.type) : '';
    })
    console.log(str)
    this.setData({
      queryType: str.join(','),
      isSaix: false,
      shaixuan:0
    })
    this.getShopLists('加载中...');
  },
  getBanner() {
    axios.reqPost('xad/getBannerList', {}, res => {
      this.setData({
        banners: res.returnObject.list
      })
    })
  },
  dumpFood() {
    wx.navigateTo({
      url: './search/index?type=food',
    })
  },
  dumpShop() {
    wx.navigateTo({
      url: './search/index?type=shop',
    })
  },
  handleCLickPosi() {
    wx.navigateTo({
      url: './position/index',
    })
  },
  focusIpt() {
    wx.navigateTo({
      url: './search/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(utils)
    this.getShopLists('加载中...');
    this.getBanner();
	this.getSysPhone();
	//获取地理位置,设置左上角位置信息
	var _this = this;
	//获取缓存中的地址 //如果有地址就用缓存中的,如果没有就用
  try{
    var location = wx.getStorageSync('location');
    console.log('缓存中的经纬度:', location.lat, location.lng);
    if (location) {
      _map.reverseGeocoder(location.lat, location.lng, function (res) {
		  if (_this.data.optionsAdd){
				_this.setData({
					address: _this.data.optionsAdd
				})
		  }else{
			  _this.setData({
				  address: res.formatted_addresses.recommend
			  })
		  }
      });
      _this.getShopLists('加载中...');
    }else{
		_map.getLocation(function (res) {
			console.log(res);
			_map.reverseGeocoder(res.latitude, res.longitude, function (res) {
				if (_this.data.optionsAdd) {
					_this.setData({
						address: _this.data.optionsAdd
					})
				} else {
					_this.setData({
						address: res.formatted_addresses.recommend
					})
				}
			});
			_this.getShopLists('加载中...');
		});
	}

  } catch (e){
    _map.getLocation(function (res) {
      console.log(res);
      _map.reverseGeocoder(res.latitude, res.longitude, function (res) {
		  if (_this.data.optionsAdd) {
			  _this.setData({
				  address: _this.data.optionsAdd
			  })
		  } else {
			  _this.setData({
				  address: res.formatted_addresses.recommend
			  })
		  }
      });
      _this.getShopLists('加载中...');
    });
  }
// else{
		 
	// }
	  
  },
  handlePaixu() {
    this.setData({
      showFlag: false,
      shadowFlag: true

    })
  },
  onShow:function(){
    console.log(utils)
    this.getShopLists('加载中...');
    this.getBanner();
    this.getSysPhone();
    //获取地理位置,设置左上角位置信息
    var _this = this;
    //获取缓存中的地址 //如果有地址就用缓存中的,如果没有就用
    try {
      var location = wx.getStorageSync('location');
      console.log('缓存中的经纬度:', location.lat, location.lng);
      if (location) {
        _map.reverseGeocoder(location.lat, location.lng, function (res) {
			if (_this.data.optionsAdd) {
				_this.setData({
					address: _this.data.optionsAdd
				})
			} else {
				_this.setData({
					address: res.formatted_addresses.recommend
				})
			}
        });
        _this.getShopLists('加载中...');
      }else{
		  _map.getLocation(function (res) {
			  console.log(res);
			  _map.reverseGeocoder(res.latitude, res.longitude, function (res) {
				  if (_this.data.optionsAdd) {
					  _this.setData({
						  address: _this.data.optionsAdd
					  })
				  } else {
					  _this.setData({
						  address: res.formatted_addresses.recommend
					  })
				  }
			  });
			  _this.getShopLists('加载中...');
		  });
	  }

    } catch (e) {
      _map.getLocation(function (res) {
        console.log(res);
        _map.reverseGeocoder(res.latitude, res.longitude, function (res) {
			if (_this.data.optionsAdd) {
				_this.setData({
					address: _this.data.optionsAdd
				})
			} else {
				_this.setData({
					address: res.formatted_addresses.recommend
				})
			}
        });
        _this.getShopLists('加载中...');
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    wx.showNavigationBarLoading()
    this.setData({
      pageNum: 1
    })
    this.getShopLists('加载中...');
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    console.log(123)
    if (this.data.hasMoreData) {
      this.getShopLists('加载中...');
    }
  },
  onPageScroll: function(e) {
    // console.log(e.scrollTop);
  },
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom
      })
    }).exec()
  },
})